import {Vector4} from "../math/Vector4";
import {MathUtil} from "../math/MathUtil";
// @ts-ignore
import * as TGA from 'tgaimage';
import {InterpolateUtil} from "../math/InterpolateUtil";

export class Texture {
    width: number;
    height: number;
    data: Float32Array;

    loadImageData(imageData: ImageData) {
        this.width = imageData.width;
        this.height = imageData.height;
        this.data = new Float32Array(imageData.data.length);
        for (let i = 0; i < this.data.length; i++) {
            this.data[i] = imageData.data[i] / 255;
        }
        return this;
    }

    private getPointData(x: number, y: number) {
        const offset = ((this.height-y)*this.width + x) * 4;
        return new Vector4(
            this.data[offset + 0],
            this.data[offset + 1],
            this.data[offset + 2],
            this.data[offset + 3]
        );
    }

    sample(u: number, v: number): Vector4 {
        // 双线性插值
        // 先使用简单的方式
        u *= this.width;
        v *= this.height;
        u = MathUtil.clamp(u, 0, this.width-1);
        v = MathUtil.clamp(v, 0, this.height-1);
        // return  this.getPointData(u, v);
        const u0 = Math.floor(u), u1 = Math.ceil(u), v0 = Math.floor(v), v1 = Math.ceil(v);
        const d00 = this.getPointData(u0, v0);
        const d01 = this.getPointData(u0, v1);
        const d10 = this.getPointData(u1, v0);
        const d11 = this.getPointData(u1, v1);
        const A0 = InterpolateUtil.interpolateLine(v, v0, v1, d00, d01);
        const A1 = InterpolateUtil.interpolateLine(v, v0, v1, d10, d11);
        return InterpolateUtil.interpolateLine(u, u0, u1, A0, A1)
    }

    static createImageTexture(url: string): Promise<Texture> {
        return new Promise<Texture>((resolve, reject) => {
            const img =new Image();
            // 给临时图片设置真实的路径
            img.src=url;
            // 给临时图片绑定onload事件
            img.onload=function(){
                // 将真实地址传给options中的images对象
                const canvas = document.createElement("canvas") as HTMLCanvasElement;
                canvas.width = img.width;
                canvas.height = img.height;
                const context = canvas.getContext('2d') as CanvasRenderingContext2D;
                context.drawImage(img, 0, 0);
                resolve(new Texture().loadImageData(context.getImageData(0, 0, img.width, img.height)));
            }
            // 如果加载失败，绑定onerror
            img.onerror=function(e){
                reject(e);
            }
        })
    }

    static async createTagImageTexture(url: string) {
        const tga = TGA.imageWithURL(url)
        await tga.didLoad;
        const canvas = tga.canvas as HTMLCanvasElement;
        // document.body.appendChild(tga.image);
        const context = canvas.getContext('2d') as CanvasRenderingContext2D;
        return new Texture().loadImageData(context.getImageData(0, 0, canvas.width, canvas.height));
    }
}


